import path from 'path'
import { createRequire } from 'module'
import dayjs from 'dayjs'

export default () => {
	let config = {}
	let version = ''

	const currentTime = dayjs().format("YYYY-MM-DD HH:mm:ss")

	return {
		name: 'vite-log-time',
		configResolved(_config) {
			config = _config
			const require = createRequire(import.meta.url)
			version = require(path.resolve(config.root, 'package.json')).version
		},
		transform(code, id) {
			if (id.endsWith('src/main.js')) {
				const info = {
					mode: config.mode,
					currentTime,
					version,
				}
				return {
					code: `
            console.log('构建信息:', '${JSON.stringify(info)}')
            ${code}
          `,
					map: null
				}
			}
		},
	}
}